/*
 * Copyright (c) 2020-2030 Sishun.Co.Ltd. All Rights Reserved.
 */
package com.demo.elasticsearch.service;

import com.alibaba.fastjson.JSON;
import com.demo.elasticsearch.pojo.Context;
import com.demo.elasticsearch.utils.ParseHtmlUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ：lvfeilong
 * @version ：
 * @description ：
 * @program ：elasticsearch-study-jd
 * @date ：Created in 2021/6/29 20:01
 */
@Service
public class ContextServiceImpl {

    @Resource
    private RestHighLevelClient client;

    public boolean insertEsBySearch(String keyword) throws IOException {
        //解析搜索数据
        List<Context> contexts = ParseHtmlUtil.insertEsBySearch(keyword);
        if (!CollectionUtils.isEmpty(contexts)) {
            BulkRequest bulkRequest = new BulkRequest();
            for (Context context : contexts) {
                bulkRequest.add(new IndexRequest("context_index").source(JSON.toJSONString(context), XContentType.JSON));
            }
            bulkRequest.timeout(TimeValue.timeValueSeconds(5));
            BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            return !bulkResponse.hasFailures();
        }
        return false;
    }

    public List<Map<String, Object>> searchEsByKeyword(String keyword, Integer currentPage, Integer pageSize) throws IOException {
        //创建搜索请求
        SearchRequest searchRequest = new SearchRequest("context_index");
        //构造搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        TermQueryBuilder termQuery = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(termQuery);
        //设置响应时间
        sourceBuilder.timeout(TimeValue.timeValueSeconds(3));
        //设置分页
        sourceBuilder.from(currentPage);
        sourceBuilder.size(pageSize);
        searchRequest.source(sourceBuilder);
        //搜索
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        //保存搜索结果
        List<Map<String, Object>> resList = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            resList.add(hit.getSourceAsMap());
        }
        return resList;
    }

    public List<Map<String, Object>> highLightSearch(String keyword, Integer currentPage, Integer pageSize) throws IOException {//创建搜索请求
        SearchRequest searchRequest = new SearchRequest("context_index");
        //构造搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        TermQueryBuilder termQuery = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(termQuery);
        //设置响应时间
        sourceBuilder.timeout(TimeValue.timeValueSeconds(3));
        //设置分页
        sourceBuilder.from(currentPage);
        sourceBuilder.size(pageSize);
        //高亮设置
        HighlightBuilder highlighter = new HighlightBuilder();
        highlighter.field("title");
        //多个高亮显示是否开启
        highlighter.requireFieldMatch(false);
        highlighter.preTags("<span style='color:red'>");
        highlighter.postTags("</span>");
        sourceBuilder.highlighter(highlighter);
        searchRequest.source(sourceBuilder);
        //搜索
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        //保存搜索结果
        List<Map<String, Object>> resList = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            //解析高亮字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            //高亮字段替换
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if (title!=null) {
                Text[] fragments = title.getFragments();
                StringBuilder newTitle = new StringBuilder();
                for (Text fragment : fragments) {
                    newTitle.append(fragment);
                }
                sourceAsMap.put("title", newTitle.toString());
            }
            resList.add(sourceAsMap);
        }
        return resList;
    }
}